<template>
  <div class="orders">
    <van-sticky>
      <van-dropdown-menu>
        <van-dropdown-item 
          v-model="statusFilter" 
          :options="statusOptions" 
        />
        <van-dropdown-item 
          v-model="timeFilter" 
          :options="timeOptions" 
        />
      </van-dropdown-menu>
    </van-sticky>
    
    <van-pull-refresh 
      v-model="refreshing" 
      @refresh="onRefresh"
    >
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-card
          v-for="order in orders"
          :key="order.id"
          :title="`订单号: ${order.orderNo}`"
          :desc="order.productName"
          :price="order.price"
          currency="¥"
        >
          <template #thumb>
            <div class="placeholder-thumb"></div>
          </template>
          
          <template #tags>
            <van-tag :type="getOrderStatusType(order.status)">{{ order.status }}</van-tag>
          </template>
          
          <template #footer>
            <div class="order-footer">
              <span class="order-date">{{ order.date }}</span>
              <div class="order-actions">
                <van-button size="mini" @click="viewOrder(order)">查看</van-button>
                <van-button 
                  v-if="order.status === '待支付'" 
                  size="mini" 
                  type="primary" 
                  @click="editOrder(order)"
                >
                  编辑
                </van-button>
                <van-button 
                  v-if="order.status === '待支付'" 
                  size="mini" 
                  type="danger" 
                  @click="deleteOrder(order)"
                >
                  删除
                </van-button>
              </div>
            </div>
          </template>
        </van-card>
      </van-list>
    </van-pull-refresh>
    
    <van-empty 
      v-if="orders.length === 0 && !loading" 
      description="暂无订单数据" 
    />
    
    <!-- 订单详情弹窗 -->
    <van-popup 
      v-model:show="showOrderDetail" 
      position="bottom" 
      :style="{ height: '80%' }"
      round
    >
      <van-cell-group>
        <van-nav-bar
          title="订单详情"
          left-text="关闭"
          @click-left="showOrderDetail = false"
        />
        
        <van-cell title="订单号" :value="currentOrder.orderNo" />
        <van-cell title="下单时间" :value="currentOrder.date" />
        <van-cell title="订单状态">
          <template #default>
            <van-tag :type="getOrderStatusType(currentOrder.status)">{{ currentOrder.status }}</van-tag>
          </template>
        </van-cell>
        
        <van-cell-group title="商品信息">
          <van-cell :title="currentOrder.productName" :value="`¥${currentOrder.price}`" />
          <van-cell title="数量" :value="currentOrder.quantity" />
          <van-cell title="总价">
            <template #value>
              <span class="total-price">¥{{ (currentOrder.price * currentOrder.quantity).toFixed(2) }}</span>
            </template>
          </van-cell>
        </van-cell-group>
        
        <van-cell-group title="用户信息">
          <van-cell title="用户昵称" :value="currentOrder.userName" />
          <van-cell title="联系方式" :value="currentOrder.userPhone" />
        </van-cell-group>
        
        <van-cell-group title="操作">
          <van-cell 
            v-if="currentOrder.status === '待支付'" 
            title="编辑订单" 
            is-link 
            @click="editCurrentOrder" 
          />
          <van-cell 
            v-if="currentOrder.status === '待支付'" 
            title="取消订单" 
            is-link 
            @click="cancelOrder" 
          />
          <van-cell 
            v-if="currentOrder.status === '待支付'" 
            title="标记为已支付" 
            is-link 
            @click="markAsPaid" 
          />
        </van-cell-group>
      </van-cell-group>
    </van-popup>
    
    <!-- 编辑订单表单 -->
    <van-popup 
      v-model:show="showEditForm" 
      position="bottom" 
      :style="{ height: '80%' }"
      round
    >
      <van-form @submit="onSaveOrder">
        <van-nav-bar
          :title="editingOrder ? '编辑订单' : '新增订单'"
          left-text="取消"
          right-text="保存"
          @click-left="showEditForm = false"
          @click-right="onSaveOrder"
        />
        
        <div class="form-content">
          <van-cell-group inset>
            <van-field
              v-model="orderForm.productName"
              name="商品名称"
              label="商品名称"
              placeholder="请输入商品名称"
              :rules="[{ required: true, message: '请输入商品名称' }]"
            />
            
            <van-field
              v-model.number="orderForm.price"
              name="单价"
              label="单价"
              type="number"
              placeholder="请输入单价"
              :rules="[{ required: true, message: '请输入单价' }]"
            />
            
            <van-field
              v-model.number="orderForm.quantity"
              name="数量"
              label="数量"
              type="number"
              placeholder="请输入数量"
              :rules="[{ required: true, message: '请输入数量' }]"
            />
            
            <van-field
              v-model="orderForm.userName"
              name="用户昵称"
              label="用户昵称"
              placeholder="请输入用户昵称"
              :rules="[{ required: true, message: '请输入用户昵称' }]"
            />
            
            <van-field
              v-model="orderForm.userPhone"
              name="联系方式"
              label="联系方式"
              type="tel"
              placeholder="请输入联系方式"
              :rules="[{ required: true, message: '请输入联系方式' }]"
            />
            
            <van-field name="picker" label="订单状态" is-link readonly @click="showStatusPicker = true">
              <template #input>
                <span>{{ orderForm.status }}</span>
              </template>
            </van-field>
          </van-cell-group>
        </div>
      </van-form>
    </van-popup>
    
    <!-- 状态选择器 -->
    <van-popup v-model:show="showStatusPicker" round position="bottom">
      <van-picker
        :columns="statusColumns"
        @confirm="onConfirmStatus"
        @cancel="showStatusPicker = false"
      />
    </van-popup>
    
    <van-button 
      round 
      type="primary" 
      class="add-btn"
      @click="addOrder"
    >
      <van-icon name="plus" /> 新增订单
    </van-button>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { showToast, showDialog } from 'vant'

const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)
const showOrderDetail = ref(false)
const showEditForm = ref(false)
const showStatusPicker = ref(false)
const editingOrder = ref(null)
const currentOrder = ref({})

const statusFilter = ref('all')
const timeFilter = ref('all')

const statusOptions = [
  { text: '全部状态', value: 'all' },
  { text: '待支付', value: 'pending' },
  { text: '已支付', value: 'paid' },
  { text: '已完成', value: 'completed' },
  { text: '已取消', value: 'cancelled' }
]

const timeOptions = [
  { text: '全部时间', value: 'all' },
  { text: '今天', value: 'today' },
  { text: '近7天', value: 'week' },
  { text: '近30天', value: 'month' }
]

const statusColumns = [
  { text: '待支付', value: '待支付' },
  { text: '已支付', value: '已支付' },
  { text: '已完成', value: '已完成' },
  { text: '已取消', value: '已取消' }
]

const orders = ref([
  {
    id: 1,
    orderNo: '20230820001',
    productName: '三亚亚龙湾度假套餐',
    price: 888.00,
    quantity: 2,
    status: '已支付',
    date: '2023-08-20 14:30',
    userName: '张三',
    userPhone: '13800138000'
  },
  {
    id: 2,
    orderNo: '20230819002',
    productName: '北京故宫门票',
    price: 60.00,
    quantity: 4,
    status: '已完成',
    date: '2023-08-19 10:15',
    userName: '李四',
    userPhone: '13900139000'
  },
  {
    id: 3,
    orderNo: '20230818003',
    productName: '上海迪士尼门票',
    price: 399.00,
    quantity: 3,
    status: '待支付',
    date: '2023-08-18 09:45',
    userName: '王五',
    userPhone: '13700137000'
  },
  {
    id: 4,
    orderNo: '20230817004',
    productName: '黄山风景区门票',
    price: 230.00,
    quantity: 1,
    status: '已取消',
    date: '2023-08-17 16:20',
    userName: '赵六',
    userPhone: '13600136000'
  }
])

const orderForm = reactive({
  productName: '',
  price: null,
  quantity: 1,
  status: '待支付',
  userName: '',
  userPhone: ''
})

const getOrderStatusType = (status) => {
  switch (status) {
    case '待支付': return 'warning'
    case '已支付': return 'primary'
    case '已完成': return 'success'
    case '已取消': return 'default'
    default: return 'default'
  }
}

const onRefresh = () => {
  setTimeout(() => {
    refreshing.value = false
    showToast('刷新成功')
  }, 1000)
}

const onLoad = () => {
  setTimeout(() => {
    loading.value = false
    finished.value = true
  }, 1000)
}

const viewOrder = (order) => {
  currentOrder.value = order
  showOrderDetail.value = true
}

const editOrder = (order) => {
  editingOrder.value = order
  Object.assign(orderForm, order)
  showEditForm.value = true
}

const editCurrentOrder = () => {
  showOrderDetail.value = false
  editOrder(currentOrder.value)
}

const addOrder = () => {
  editingOrder.value = null
  resetForm()
  showEditForm.value = true
}

const deleteOrder = (order) => {
  showDialog({
    title: '确认删除',
    message: `确定要删除订单 "${order.orderNo}" 吗？`,
    showCancelButton: true
  }).then(() => {
    const index = orders.value.findIndex(item => item.id === order.id)
    if (index !== -1) {
      orders.value.splice(index, 1)
      showToast('删除成功')
    }
  }).catch(() => {
    // 取消操作
  })
}

const cancelOrder = () => {
  currentOrder.value.status = '已取消'
  showToast('订单已取消')
}

const markAsPaid = () => {
  currentOrder.value.status = '已支付'
  showToast('订单已标记为已支付')
}

const onConfirmStatus = (option) => {
  orderForm.status = option.selectedValues[0]
  showStatusPicker.value = false
}

const onSaveOrder = () => {
  if (!orderForm.productName || !orderForm.price || !orderForm.userName || !orderForm.userPhone) {
    showToast('请填写必填项')
    return
  }
  
  if (editingOrder.value) {
    // 编辑模式
    const index = orders.value.findIndex(item => item.id === editingOrder.value.id)
    if (index !== -1) {
      orders.value[index] = { ...editingOrder.value, ...orderForm }
    }
    showToast('编辑成功')
  } else {
    // 新增模式
    const newOrder = {
      id: Date.now(),
      orderNo: `2023${Math.floor(Math.random() * 1000000).toString().padStart(6, '0')}`,
      date: new Date().toLocaleString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      }).replace(/\//g, '-'),
      ...orderForm
    }
    orders.value.unshift(newOrder)
    showToast('添加成功')
  }
  
  showEditForm.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(orderForm, {
    productName: '',
    price: null,
    quantity: 1,
    status: '待支付',
    userName: '',
    userPhone: ''
  })
  editingOrder.value = null
}
</script>

<style scoped>
.orders {
  padding-bottom: 50px;
}

.placeholder-thumb {
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
  border-radius: 8px;
}

.order-footer {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.order-date {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.total-price {
  color: #ee0a24;
  font-weight: bold;
}

.add-btn {
  position: fixed;
  bottom: 70px;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
}

.form-content {
  padding-top: 46px;
}
</style>